"""
Author: Chip Chapin <cchapin@gmail.com>
For More Info: http://code.google.com/p/seq-to-qt/
Last Updated: 2010-02-05

File Sequence: A collection of files in a single directory where the filenames
consist of a common prefix and a numeric suffix.
  For example, MT0001.jpg, MT0002.jpg, MT0003.jpg ...

Chunking: Dividing a file sequence into shorter subsequences by moving some of
them into other directories.

UnChunking: Putting the subsequences back into a single sequence by moving them
back into the original directory.
"""
import glob
import os
import seq_to_qt
import shutil
import sys

def _usage(message=None):
    """Print usage message and exit."""
    if message:
        print message
    print "Usage: seq_unchunk.py sequenceFile"
    print (
"\nSequences have sequentially numbered file names like\n" +
"    Foo-001.jpg, Foo-002.jpg...\n" +
"sequenceFile: Path to what would have been an original file in the sequence.");
    sys.exit(2)

def _rmdir_if_empty(dir_path):
    """Delete a directory if it's empty."""
    try:
        os.rmdir(dir_path)
    except OSError:
        print "Not empty: " + dir_path
    else:
        print "Removed: " + dir_path
    
def _get_chunks(seq_path):
    """Look for directories that look like splits from seq_dir."""
    chunk_candidates = glob.glob(seq_path + "-[0-9]")
    chunk_candidates.extend(glob.glob(seq_path + "-[0-9][0-9]"))
    return chunk_candidates

def _move_seq_files(seq_name, src, dst):
    """Move all files matching seq_name pattern from src to dst directories."""
    for srcpath in glob.glob(os.path.join(src, seq_name + "*")):
        fname = os.path.basename(srcpath)
        dstpath = os.path.join(dst, fname)
        # print srcpath + " => " + dstpath
        shutil.move(srcpath, dstpath)

def unchunk(path):
    """Unchunk a single sequence."""
    (seq_path, seq_file) = os.path.split(os.path.abspath(path))
    parent_dir = os.path.dirname(seq_path)
    seq_name = seq_to_qt.seq_name_from_filename(seq_file)
    for chunk_name in _get_chunks(seq_path):
        chunk = os.path.join(parent_dir, chunk_name)
        _move_seq_files(seq_name, chunk, seq_path)
        _rmdir_if_empty(chunk)
  
def unchunk_sequences(parent_dir, sequences):
    """Unchunk a collection of sequences.
    The sequence list is in the same format orginally used to convert.
    """
    for seq in sequences:
        seq_path = os.path.join(parent_dir, seq[0], seq[1])
        print seq_path
        unchunk(seq_path)
        
          
def main(argv):
    """Main Program"""
    if (len(argv) < 2):
        _usage("No arguments")
    unchunk(argv[1])
     
if __name__ == "__main__":
    main(sys.argv)
